<template>
    <el-button type="primary" style="margin-right:10px" plain  @click="addCategory">新增</el-button>
    <div class="custom-tree-container">
    <el-tree
            :data="dataSource"
            v-loading="loading"
            node-key="catId"
            :props = defaultProps
            accordion
            :expand-on-click-node="false"
    >
        <template #default="{ node, data }">
        <span class="custom-tree-node" >
          <span>{{ node.label }}</span>
            <span style="margin-left: 10px">
                <el-link style="font-size: 14px" type="primary" @click="updateCategory(node, data)" style="margin-left: 8px"> 修改 </el-link>
                 <el-popconfirm title="删除？" @confirm="deleteCategory(data.catId)"  @cancel="">
                      <template #reference>
                        <el-link style="font-size: 14px" v-if="data.children == undefined || data.children.length == 0" type="danger"
                                 style="margin-left: 8px"> 删除 </el-link>
                      </template>
                 </el-popconfirm>
            </span>
        </span>
        </template>
    </el-tree>
    </div>
    <ModCategory @reload = load :edit= edit ref="modCategory" :dataSource = dataSource />
</template>

<script setup>
    import { ref,reactive,onMounted,computed } from 'vue'
    import request from '@/utils/request.js'
    import ModCategory from '@/components/mall/ModCategory.vue'
    import moment from 'moment'
    let id = 1000
    let modCategory = ref()
    let loading = ref(true)
    let dataSource = reactive([])
    const defaultProps = {
        children: 'children',
        label: 'name',
        id:"catId"
    }
    let edit = reactive({type:"add", id:0, node:null})
    onMounted(() => {
        load()
    })

    function load() {
        request.get(`/api/category/list/tree`).then(resp => {
            dataSource.splice(0, dataSource.length)
            dataSource.push(...resp)
            loading.value = false
        })
    }
    const deleteCategory = (nodeId) => {
        debugger
        request.get(`/api/category/delete/${nodeId}`).then(resp => {
            load()
        })
    }

    function  addCategory() {
        debugger
        edit.type="add"
        modCategory.value.showDialog = true
    }
    function updateCategory(node, data) {
        debugger
        edit.type="update"
        edit.node = node
        modCategory.value.showDialog = true
    }
</script>

<style lang="css" scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>
